import wepy from 'wepy'
import { BASE_URL } from './config'

export const authLogin = () => {
  return new Promise(async (resolve, reject) => {
    let res = await wepy.login()
    wepy.request({
      url: `${BASE_URL}apis/wxLogin?code=${res.code}`,
      method: 'POST',
      data: { code: res.code },
      header: {
        'content-type': 'application/json'
      }
    }).then(({data}) => {
      if (data.status == '0') {
        let wxdata = JSON.parse(data.wxdata)
        wx.setStorageSync('session_key', wxdata.session_key);
        wx.setStorageSync('openid', wxdata.openid);
        // console.log(wx.getStorageSync('session_key'), 'session_key');
        // console.log(wx.getStorageSync('openid'), 'openid');
        resolve()
      } else {
        reject(data.msg)
      }
    })
  })
}

const doRequest = async(url, param, options) => {
  let params = {}
  let paramsurl = ''
  const trim = (v) => typeof v == 'string' ? v.replace(/(^\s+)|(\s+$)/g, '') : v
  if (param) {
    // Object.entries(param).forEach(v => {
    //   params[trim(v[0])] = trim(v[1])
    // })
    if (JSON.stringify(param).indexOf(JSON.stringify('openid')) > -1){
      let openid = param.openid || ''
      if (openid == '') {
        await authLogin()
        param.openid = wx.getStorageSync('openid')
      }
    }
    if (JSON.stringify(param).indexOf(JSON.stringify('session_key')) > -1){
      let session_key = param.session_key || ''
      if (session_key == '') {
        await authLogin()
        param.session_key = wx.getStorageSync('session_key')
      }
    }
    Object.keys(param).forEach((v, index) => {
      params[trim(v)] = trim(param[v])
      if (index === 0) {
        paramsurl = `?${trim(v)}=${param[v]}`
      } else {
        paramsurl = `${paramsurl}&${trim(v)}=${param[v]}`
      }
    })

  } else params = param
  options.loading && wx.showNavigationBarLoading()
  return new Promise((resolve, reject) => {
    wepy.request({
      url: BASE_URL + url + paramsurl,
      data: params,
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'AuthToken': wepy.getStorageSync('token')
      }
    }).then(res => {
      options.loading && (wx.hideNavigationBarLoading())
      // options.loading && (wx.hideLoading())
      let intercept = options.intercept
      res.data = {...res.data, intercept}
      resolve(res.data)
    }).catch(err => {
      options.loading && (wx.hideNavigationBarLoading())
      // options.loading && (wx.hideLoading())
      wepy.showToast({
        title: '请检查你的网络',
        icon: 'none'
      })
      resolve(err)
    })
  })
}
export const fetch = (url, param, options) => {
  let defaultOptions = {loading: true, loadingText: '数据加载中', toast: true, intercept: true}
  let newOptions = Object.assign({}, defaultOptions, options)
  return new Promise((resolve, reject) => {
    resolve(doRequest(url, param, newOptions))
  })
}
